import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {MenusService} from "./menus.service";
import {ResponseUtil} from "../../../util/response-util";
import {Menu} from "./menu";
import {MsgResult} from "../../../models/msg-result";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {TableUtil} from "../../../util/table-util";
import {API, MsgConstants} from "../../../constants/constants";
import {TreeUtil} from "../../../util/tree-util";

declare var $;

@Component({
  selector: 'app-menus',
  templateUrl: './menus.component.html'
})
export class MenusComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  /**
   * 声明实例
   */
  menu: Menu;
  /**
   * 定义数组
   * @type {Array} :存储勾选id
   */
  menuIds: Array<string> = [];

  menuId :string;

  newMenuId :string;

  cloneObj;

  table;

  treeObj;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private tableUtil: TableUtil,
              private treeUtil: TreeUtil,
              private menusService: MenusService,
              private pageSubject: PageSubject,
              private dialogService: OneDialogService,
              private responseUtil: ResponseUtil) {
  }

  proxy = {
    "menuAdd": () => this.menuAdd(),
    "menuDelete": () => this.menuDelete(),
    "forceMenuDelete": () => this.forceMenuDelete(),
    "menuUpdate": () => this.menuUpdate(),
    "menuDistribution": () => this.menuDistribution(),
    "menuClone": () => this.menuClone()
  }

  ngOnInit() {

    //初始化面包屑导航
    this.pushPage();
    //初始化表单
    this.loadMenu();

    this.initMenuZTree();
  }  //end ngOnInit

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("菜单管理", "查询", path);
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 账户列表查询
   */
  loadMenu() {
    this.table = this.tableUtil.load("one_table_menu",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '名称', align: 'left'},
        {field: "url", title: 'URL', align: 'left'},
        {field: "menuCode", title: '菜单编码', align: 'left'},
        {field: "cssName", title: '图标样式', align: 'left'},
        {field: "remark", title: '备注', align: 'left'},
        {field: "orderBy", title: '顺序', align: 'right', sortName: "ORDERBY", sortable: true},
        {field: "typeName", title: '类型名称', align: 'left'},
        {field: "type", title: '类型', visible: false, switchable: false },
        {field: "isDisplay", title: '显示', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isEnable", title: '启用', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isBlank", title: '空白页', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isExistUrl", title: '存在Url', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isExternal", title: '外部链接', align: 'left', formatter: this.yesOrNoFormat},
        {field: "creatorName", title: '创建人', align: 'left', visible: false},
        {field: "CREATE_DATE", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true, visible: false},
        {field: "editorName", title: '修改人', align: 'left', visible: false},
        {field: "MODIFIED_DATE", title: '修改日期', align: 'left', sortName: "MODIFIED_DATE", sortable: true, visible: false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_menus",
      url: API.menuPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#menuName").val();
        params.pId =  $("#menuId").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.CREATE_DATE = value.createDate || '';
            value.MODIFIED_DATE = value.modifiedDate || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'MODIFIED_DATE',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }


  /**
   * 添加页面跳转操作
   */
  menuAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 删除弹窗
   */
  menuDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    this.menuIds = this.tableUtil.getCloumns(rows, "id");
    if (this.menuIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  /**
   * 确认删除按钮
   */
  requestDelete =()=> {
    this.menusService.delMenus(this.menuIds).subscribe(
      result => this.responseUtil.success(result, this.processMenuDeletesResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 删除结果处理
   * @param result
   */
  processMenuDeletesResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
      this.initMenuZTree();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  forceMenuDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    this.menuIds = this.tableUtil.getCloumns(rows, "id");
    if (this.menuIds.length == 0) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("菜单可能正在使用，是否继续删除？", this.requestForceDelete);
    }
  }

  /**
   * 确认删除按钮
   */
  requestForceDelete = () => {
    this.menusService.forceDelMenus(this.menuIds).subscribe(
      result => this.responseUtil.success(result, this.processMenuDeletesResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 实现修改页面跳转
   */
  menuUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    this.menuIds = this.tableUtil.getCloumns(rows, "id");
    if (this.menuIds.length == 1) {
      this.router.navigate(['update', {menuId: this.menuIds[0]}], {relativeTo: this.route});
    }else {
      this.dialogService.modalInfo("请选择一条数据");
    }
  }


  /**
   * 分配操作
   */
  menuDistribution() {
    let rows = this.table.bootstrapTable('getSelections');
    this.menuIds = this.tableUtil.getCloumns(rows, "id");
    let pageType = this.tableUtil.getCloumns(rows, "type");

    if (pageType[0] == '2'){
      if (this.menuIds.length == 1) {
        this.router.navigate(['operation', {menuId: this.menuIds[0]}], {relativeTo: this.route});
      } else {
        this.dialogService.modalInfo("请选择一条数据");
      }
    }

    if( !pageType[0] || pageType[0] == "1"){
      this.dialogService.modalInfo("目录不具备拥有操作功能！");
    }
    if(!pageType[0] || pageType[0] == '0'){
      this.dialogService.modalInfo("子系统不具备拥有操作功能！");
    }
  }

  /**
   * 获取菜单数据信息
   */
  initMenuZTree() {
    this.menusService.getMenus().subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
     this.initMenusTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 把菜单格式化菜单树
   *
   * @param menus: 菜单数据
   */
  initMenusTree(menus) {
    //初始化菜单树
    let setting = {
      callback: {
        onClick: this.clickTree
      }
    };

    let zNodes =this.treeUtil.wrapToStandard(menus);
    //把树放进页面
    this.treeObj = $.fn.zTree.init($("#menuManagerZTree"), setting, zNodes);

  }

  /**
   *  菜单的点击事件
   * @param event
   * @param treeId
   * @param treeNode
   */
  clickTree = (event, treeId, treeNode) =>{
    // 获取输入框对象
    let menuId = $("#menuId");
    console.log(treeNode.id+'-----'+menuId.val());
    if(treeNode.id == menuId.val()){
      let selectedArray:Array<object> = this.treeObj.getSelectedNodes();
      if (selectedArray.length>0) {
        this.treeObj.cancelSelectedNode(selectedArray[0]);
      }
      menuId.val("");
    }else{
      menuId.val(treeNode.id);
    }
    this.search();
  }

  /**
   * 复制
   */
  menuClone(){
    let rows = this.table.bootstrapTable('getSelections');
    if (rows.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.cloneObj = rows[0];
      // 用于
      this.menuId = rows[0].id;
      this.dialogService.modalInfoWithCancelBtn("确定复制？",this.requestClone);
    }
  }
  requestClone =()=>{
    this.cloneObj.id = "";
    this.cloneObj.name = this.cloneObj.name+"_COPY";
    this.cloneObj.menuCode = this.cloneObj.menuCode+"_COPY";
    if(!this.cloneObj.hasOwnProperty("type")){
      this.cloneObj.type = "-";
    }

    this.cloneObj.pId = this.cloneObj.hasOwnProperty("pId")?this.cloneObj.pId:"";
    this.cloneObj.remark = this.cloneObj.hasOwnProperty("remark")?this.cloneObj.remark:"";
    this.cloneObj.cssName = this.cloneObj.hasOwnProperty("cssName")?this.cloneObj.cssName:"";
    this.cloneObj.url = this.cloneObj.hasOwnProperty("url")?this.cloneObj.url:"";

    this.menusService.insertMenu(this.cloneObj).subscribe(
      result => this.responseUtil.success(result, this.processMenuCloneResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 复制结果处理
   * @param result
   */
  processMenuCloneResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      //{"name":"门户管理_COPY","pId":"acf903261cc144e3953b81b7a4ee9606","id":"df03b6bb9702461a9e5121153f87ab30"}
      console.log(JSON.stringify(result.data));
      this.newMenuId = result.data.id;
      // 用于复制改菜单的所有操作按钮
      this.copyOperation();
      //刷新页面
      this.search();
      this.initMenuZTree();
      $("#menuId").val("");
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *
   */
  copyOperation(){
    this.menusService.saveOperButtonByMenuId(this.menuId,this.newMenuId).subscribe(
      result => this.responseUtil.success(result, this.processCopyOperResult),
      message => this.responseUtil.error(message)
    );
  }

  processCopyOperResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

}
